package com.example.service.impl;

import com.example.dao.TbFileMapper;
import com.example.dto.FileResult;
import com.example.dto.FileResultEnum;
import com.example.entity.TbFile;
import com.example.service.FileService;
import com.example.util.MD5Util;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

/**
 * <p>文件上传</p>
 * Created by zhezhiyong@163.com on 2018/7/24.
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Autowired
    protected FastFileStorageClient storageClient;

    @Value("${imageServerBaseUrl}")
    private String imageServerBaseUrl;

    @Resource
    private TbFileMapper tbFileMapper;

    @Override
    public FileResult uploadPic(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return FileResultEnum.SUCESS.result(1, "图片为空");
            }
            //取图片扩展名
            String originalFilename = file.getOriginalFilename();
            //取扩展名不要“.”
            assert originalFilename != null;
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String dir = System.getProperty("user.dir", "temp");
            file.transferTo(new File(dir +File.separator+ file.getOriginalFilename()));
            File tempFile = new File(dir + File.separator + file.getOriginalFilename());
            String md5 = MD5Util.getFileMD5(tempFile);
            TbFile tbFile = new TbFile();
            tbFile.setFileName(originalFilename);
            tbFile.setExt(extName);
            tbFile.setFileMd5(md5);

            Example example = new Example(TbFile.class);
            Example.Criteria criteria = example.createCriteria();
            if (StringUtils.isNotEmpty(tbFile.getFileMd5())) {
                criteria.andEqualTo("fileMd5", tbFile.getFileMd5());
            }

            List<TbFile> fileList = tbFileMapper.selectByExample(example);
            if (fileList.size() == 0){
                InputStream input = new FileInputStream(tempFile);
                // 上传文件和Metadata
                StorePath path = storageClient.uploadFile(input, tempFile.length(), extName, null);
                tbFile.setFileGroup(path.getGroup());
                tbFile.setPath(path.getFullPath());
                tbFile.setFileSize(Math.toIntExact(tempFile.length()));
                tbFile.setFileMd5(md5);
                tbFileMapper.insert(tbFile);
            }else {
                tbFile = fileList.get(0);
            }
            if (tempFile.delete()){
                log.info("{}, 临时文件删除成功", tempFile.getName());
            }
            return FileResultEnum.SUCESS.result(0, imageServerBaseUrl + tbFile.getPath());
//            http://118.24.14.149:8088/group1/M00/00/00/rBsAD1tXQoqAXzb8AAcRQ2l81gM066.jpg
        } catch (Exception e) {
            log.error("上传图片异常:", e);
            return FileResultEnum.FAIL.result(0, "图片上传失败");
        }
    }

}
